package cn.iocoder.common.utils.common.system.util;

import cn.iocoder.common.utils.common.exception.JeecgBootException;
import cn.iocoder.common.utils.common.system.vo.UserInfo;
import cn.iocoder.common.utils.common.util.SpringContextUtils;
import cn.iocoder.common.utils.common.util.json.JacksonUtils;
import cn.iocoder.common.utils.common.util.oConvertUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Objects;

/**
 * @Author Scott
 * @Date 2018-07-12 14:23
 * @Desc JWT工具类
 **/
public class JwtUtil {

	// 过期时间30分钟
	public static final long EXPIRE_TIME = 30 * 60 * 1000;

    public static final long EXPIRE_TIME_MEMBER = 43200 * 60 * 1000;


    /**
	 * 校验token是否正确
	 *
	 * @param token  密钥
	 * @param secret 用户的密码
	 * @return 是否正确
	 */
	public static boolean verify(String token, String username, String secret) {
		try {
			// 根据密码生成JWT效验器
			Algorithm algorithm = Algorithm.HMAC256(secret);
			JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
			// 效验TOKEN
			DecodedJWT jwt = verifier.verify(token);
			return true;
		} catch (Exception exception) {
			return false;
		}
	}

	/**
	 * 获得token中的信息无需secret解密也能获得
	 *
	 * @return token中包含的用户名
	 */
	public static String getUsername(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			return jwt.getClaim("username").asString();
		} catch (JWTDecodeException e) {
			return null;
		}
	}

    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
	public static UserInfo getUserInfo(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			return (UserInfo) JacksonUtils.parseObject(jwt.getClaim("userInfo").asString(),UserInfo.class);
		} catch (Exception e) {
			return null;
		}
	}


	/**
	 * 生成签名,5min后过期
	 *
	 * @param username 用户名
	 * @param secret   用户的密码
	 * @return 加密的token
	 */
	public static String sign(String username, String secret,String userId) {
		Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
		Algorithm algorithm = Algorithm.HMAC256(secret);
		// 附带username信息
		return JWT.create().withClaim("username", username).withClaim("userId",userId).withExpiresAt(date).sign(algorithm);

	}
	public static String sign(UserInfo userInfo) {
		Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME_MEMBER);
		Algorithm algorithm = Algorithm.HMAC256(userInfo.getUserName());
		// 附带username信息
		return JWT.create().withClaim("userInfo", JacksonUtils.toJSONString(userInfo)).withExpiresAt(date).sign(algorithm);

	}

	/**
	 * 根据request中的token获取用户账号
	 * 
	 * @param
	 * @return
	 * @throws JeecgBootException
	 */
	public static String getUserNameByToken() throws JeecgBootException {
        return getUserInfoByToken().getUserName();
	}
	public static UserInfo getUserInfoByToken() throws JeecgBootException {
		HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull( RequestContextHolder.getRequestAttributes())).getRequest();
		String accessToken = request.getHeader("X-Access-Token");
		UserInfo userInfo = getUserInfo(accessToken);
		if (userInfo==null) {
		    String userId=getUserId(accessToken);
		    if (userId==null) {
                throw new JeecgBootException("未获取到用户");
            }else {
		        UserInfo userInfo1=new UserInfo();userInfo1.setUserId(userId);
		        return  userInfo1;
            }
		}
		return userInfo;
	}
    public static String getUserNameByToken(HttpServletRequest request) throws JeecgBootException {
        String accessToken = request.getHeader("X-Access-Token");
        String username = getUsername(accessToken);
        if (oConvertUtils.isEmpty(username)) {
            throw new JeecgBootException("未获取到用户");
        }
        return username;
    }
	/**
	  *  从session中获取变量
	 * @param key
	 * @return
	 */
	public static String getSessionData(String key) {
		//${myVar}%
		//得到${} 后面的值
		String moshi = "";
		if(key.indexOf("}")!=-1){
			 moshi = key.substring(key.indexOf("}")+1);
		}
		String returnValue = null;
		if (key.contains("#{")) {
			key = key.substring(2,key.indexOf("}"));
		}
		if (oConvertUtils.isNotEmpty(key)) {
			HttpSession session = SpringContextUtils.getHttpServletRequest().getSession();
			returnValue = (String) session.getAttribute(key);
		}
		//结果加上${} 后面的值
		if(returnValue!=null){returnValue = returnValue + moshi;}
		return returnValue;
	}
	




    public static String getUserIdByToken() {
		return getUserInfoByToken()==null?null:getUserInfoByToken().getUserId();
    }
}
